<?php
 
//作者 吴俊源
if (isset($_GET['GLOBALS']) || isset($_POST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
    die('system error');
}
if (@ini_get('magic_quotes_sybase') != 0) @ini_set('magic_quotes_sybase', 0);
//商品查询时用于属性ID重新排列，生成查询条件
function parseAttrId($arr){
	$ret = array();
	parsespec('',$arr,$ret);
	return $ret;
}
function spec_price($spec){
	if(empty($spec)){
		return 0;
	}
	$spec_str = array();
	if(is_array($spec)){
		parsespec('',$spec, $spec_str);
	}else{
		$spec = explode(';',$spec);
		parsespec('',$spec, $spec_str);
	} 
	return $spec_str;
}
function parsespec($first = '', $arr, &$results = array())
{
        $len = count($arr);
        if($len == 1) {
                $results[] = $first . $arr[0];
        } else {
                for($i=0; $i<$len; $i++) {
                        $tmp = $arr[0];
                        $arr[0] = $arr[$i];
                        $arr[$i] = $tmp;
                        parsespec($first.$arr[0].';', array_slice($arr, 1), $results);
                }
        }
}
//访问量
//访问次数
function count_ip(){
	if($_SESSION['ips_id']){
    
	$path=$_SERVER['DOCUMENT_ROOT'].'/Public/Uploads/click/'.$_SESSION['ips_id']; //文件地址
	if(!file_exists($path)){ mkdir($path,777,true);}

	$myfile =fopen($path.'/ipcount.txt','a+');
	fwrite($myfile, 'm');
	$str=file_get_contents($path."/ipcount.txt");
	$ip=$_SERVER["REMOTE_ADDR"];
	$ips = $_SERVER["REMOTE_ADDR"]."\n";
	$s=strpos($str,$ip);
 
	if($s >0){}else{fwrite($myfile, $ips );} 

	fclose($myfile);

	$a=count(file($path.'/ipcount.txt'))-1; //访问人数

	$b=substr_count($str,'m'); //访问次数
 
 	 $Vcard=M('Vcard');
	 $where=$_SESSION['ips_id'];
	 $data['ip']=$a;
	 $data['ips']=$b;
	 $Vcard->where("member_id = $where")->data($data)->save();
	 
	 return true;
	 } 
	 
  	}
  		


//生成树形
function getdeepstr($int) {
    if ($int == 0) {
        return '';
    } else {
        $str = '∟';
        for ($i = 0; $i < $int; $i++) {
            $str = '　　' . $str;
        }
        return $str;
    }
}
//获取商品属性
function getAttrByProdutctId($ids) {
    $db = M('Product_stock');
    //$result = $db->
    
}
//获取系统设置项
function getSysVal($name) {
    if (S($name)) {
        $result = S($name);
    } else {
        $db = M("Setting_extends");
		if(__SITEID__ == ''){
			$result = $db->where(array(
            'site_id' => __ADMINSITEID__,
            'name' => $name
           ))->find();
		}else{
			$result = $db->where(array(
            'site_id' => __SITEID__,
            'name' => $name
           ))->find();
		   if(!$result['val']){
		   $result = $db->where(array(
            'site_id' => __RELATEID__,
            'name' => $name
           ))->find();}
		}
        S($name, $result['val']);
        $result = S($name);
    }
	
	
	
	
    return $result;
}
//获取缩略图路径
function getThumbPath($path,$R = 2, $thumb = true) {
	if(strpos($path, '/Uploads') == 0){
		$path = '/Public'.$path;
	}
	if(intval($R) === 2){return $path;}
    $fpath = pathinfo($path, PATHINFO_DIRNAME);
	if($R){
		$R = 'R';
	}else{
		$R = '';
	}
    $fname = 'thumb_' .$R. pathinfo($path, PATHINFO_BASENAME);
	
	$src = $_SERVER['DOCUMENT_ROOT'].''.$path;
	$thumb = $_SERVER['DOCUMENT_ROOT'].''.$fpath . '/' . $fname;
	if(!is_file($thumb)){
		//echo $thumb;
		import("ORG.Util.Image");
		if($R){
			Image::thumbR($src,$thumb,'',500,500,true);
		}else{
			Image::thumb($src,$thumb,'',500,500,true);
		}
    }
	
	$uploadtype = C('UPLOAD_TYPE');
	$url = C($uploadtype);
	$fpath = $url['serviceUrl'].$fpath; 
	
    return $fpath . '/' . $fname;
}


//内容反转义
function rstr($str) {
    $str = htmlspecialchars_decode($str);
    return stripslashes($str);
}
//生成网站头部信息SEO
function mate($info = array()) {
    $title = empty($info['title']) ? getSysVal('sitename') : $info['title'];
    $keywords = empty($info['keywords']) ? getSysVal('keywords') : $info['keywords'];
    $descrition = empty($info['description']) ? getSysVal('description') : $info['description'];
    $str = "<title>" . $title . "</title><meta name=\"keywords\" content=\"" . $keywords . "\"/><meta name=\"description\" content=\"" . $descrition . "\"/>";
    return $str;
}
//获取页面的分享LOGO
function getPageLogo($info = ''){
	$logo = empty($info) ? getSysVal('logo') : $info;
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = "$protocol$_SERVER[HTTP_HOST]";
	return $url.__PUBLIC__.$logo;
}
//获取页面标题
function getPageTitle($info = ''){
	$title = empty($info) ? getSysVal('sitename') : $info;
	return $title;
}
//获取页面描述
function getPageDescription($info = ''){
	$description = empty($info) ? getSysVal('description') : $info;
	return $description;
}



//清除缓文件
function clearCache($siteid) {
    $data = MyScandir(DATA_PATH);
    foreach ($data as $k => $v) {
        $siteidf = explode('_', $v);
        if ($k > 1 && $siteidf[0] == $siteid) {
			
            unlink(DATA_PATH . $v);
        }
    }
    $temp_list = M('Setting_extends')->where(array(
        'site_id' => $siteid
    ))->select();
    foreach ($temp_list as $k => $v) {
        unlink(TEMP_PATH . md5($siteid . '_' . $v['name']) . '.php');
    }
	//更新模块数据
	$modulesList = M('Modules') -> where(array('site_id' => $siteid)) -> select();
	foreach($modulesList as $v){
		reloadModulesList($v, $siteid);
		$arr = explode('_',$v['dataname']);

		if($arr[0] == 'main'){
			//更新组数据
			M('Modules') -> where(array('site_id' => $siteid, 'dataname' => $arr[1])) -> data(array('content' => $v['content'])) -> save();
			
		}
	}
    return true;
}
//生成百度站点地图
function sitemapxml() {
    $news = D('News');
    $today = date("Y-m-d", time());
    $yesterday = mktime(0, 0, 0, date("m") , date("d") - 1, date("Y"));
    $lastweek = strtotime("-1 week");
    //$link = M();
    //$yesterdayArr = $link ->query("select * from pre_sethouse where status=1 and time>$yesterday"); //昨天
    //$lastweekArr = $link ->query("select * from pre_sethouse where status=1 and time>$lastweek"); //上周
    //$url = "http://www.xxx.com/House/housecontent/id/";
    $newsArr = $news->__list('n', 'c', 'm', 'n.update_time>' . $yesterday . ' and n.status=1', 'n.sort,n.id desc', '200');
    //echo $news->getLastSql();
    //dump($newsArr);
    foreach ($newsArr as $k => $v) {
        $data_array[$k]['loc'] = U('/' . $v['category_name'] . '/' . $v['id']);
        $data_array[$k]['lastmod'] = $today;
        $data_array[$k]['changefreq'] = 'always';
        $data_array[$k]['priority'] = '0.6';
        $data_array[$k]['data'] = '<display></display>';
    }
    $content = '<?xml version="1.0" encoding="UTF-8"?><urlset>' . chr(13) . '';
    $content.= '<url>
<loc>' . $_SERVER['SERVER_NAME'] . '</loc>
<lastmod>' . $today . '</lastmod>
<changefreq>always</changefreq>
<priority>0.9</priority>
<data><display></display></data>
</url>' . chr(13);
    foreach ($data_array as $data) {
        $content.= create_item($data);
    }
    $content.= '</urlset>';
    $fp = fopen('sitemap.xml', 'w+');
    fwrite($fp, $content);
    fclose($fp);
}
function create_item($data) {
    $item = "<url>\n";
    $item.= "<loc>" . $data['loc'] . "</loc>\n";
    $item.= "<lastmod>" . $data['lastmod'] . "</lastmod>\n";
    $item.= "<changefreq>" . $data['changefreq'] . "</changefreq>\n";
    $item.= "<priority>" . $data['priority'] . "</priority>\n";
    $item.= "<data>" . $data['data'] . "</data>\n";
    $item.= "</url>\n";
    return $item;
}
//无限级导航
function getMultiNavTree($pid,$position = 'top',$class='') {
    $str = '';
    $cate = M('Nav');
    $re = $cate->where(array(
        'status' => 1,
        'pid' => $pid,
        'site_id' => __SITEID__,
		'position' => $position
    ))->order('sort')->select();
    if (!is_array($re)) {
        return $re;
    } else {
        foreach ($re as $k => $v) {
			if($v['target'] == 0){
				$target = '';
			}else{
				$target = '_blank';
			}
			
            $str.= '<li><a style="position:relative;" href="' . $v['link'] . '" target="'.$target.'" title="'.$v['title'].'">' . $v['title'] . '<span style="position:absolute; width:30px; height:
			30px; top:-8px; right:0px; display:block; background:url(__PUBLIC__'.$v['img_url'].') no-repeat center center;"></span></a>';
            $str.= getMultiNavTree($v['id'],$position, $class);
            $str.= '</li>';
        }
        return '<ul class="'.$class.'">' . $str . '</ul>';
    }
}
//获取无限极分类树
function getMultiCateTree($pid, $class = '') {
    $str = '';
    $cate = M('Category');
    $re = $cate->where(array(
        'status' => 1,
        'pid' => $pid,
        'site_id' => __RELATEID__
    ))->order('sort')->select();
	
	

	
    if (!is_array($re)) {
        return $re;
    } else {
        foreach ($re as $k => $v) {
			if($v['out_link']!=''){
				$str.= '<li><a href="' . __APP__  . $v['out_link'] . '">' . $v['title'] . '</a>';
			}else{
                $str.= '<li><a href="' . __APP__ . '/' . $v['name'] . '">' . $v['title'] . '</a>';
			}
            $str.= getMultiCateTree($v['id'],$class);
            $str.= '</li>';
        }
        return '<ul class="' . $class . '">' . $str . '</ul>';
    }
}//获取无限极分类树
function getMultiProductCateTree($pid, $class = '') {
    $str = '';
    $cate = M('Product_category');
    $re = $cate->where(array(
        'status' => 1,
        'pid' => $pid,
        'site_id' => __SITEID__
    ))->order('sort')->select();
    if (!is_array($re)) {
        return $re;
    } else {
        foreach ($re as $k => $v) {
			if($v['out_link']!=''){
				$str.= '<li><a href="' . __APP__  . $v['out_link'] . '">' . $v['title'] . '</a>';
			}else{
                $str.= '<li><a href="' . __APP__ . '/' . $v['name'] . '">' . $v['title'] . '</a>';
			}
            $str.= getMultiProductCateTree($v['id'],$class);
            $str.= '</li>';
        }
        return '<ul class="' . $class . '">' . $str . '</ul>';
    }
}
//获取无限极分类树(英文)
function en_getMultiCateTree($pid, $class = '') {
    $str = '';
    $cate = M('Category');
    $re = $cate->where(array(
        'status' => 1,
        'pid' => $pid,
        'site_id' => __RELATEID__
    ))->order('sort')->select();
    if (!is_array($re)) {
        return $re;
    } else {
        foreach ($re as $k => $v) {
			if($v['out_link']!=''){
				$str.= '<li><a href="' . __APP__  . $v['out_link'] . '">' . $v['en_title'] . '</a>';
			}else{
                $str.= '<li><a href="' . __APP__ . '/' . $v['name'] . '">' . $v['en_title'] . '</a>';
			}
            $str.= getMultiCateTree($v['id']);
            $str.= '</li>';
        }
        return '<ul class="' . $class . '">' . $str . '</ul>';
    }
}
//生成无限极分类缓存
function SMultiCateTree($pid) {
    $str = md5('Category' . $pid);
    if (S($str)) {
        return S($str);
    } else {
        $data = getMultiCateTree($pid);
        S($str, $data);
        return $data;
    }
}


function cut_content($arr, $sublen, $start = 0, $lastStr = '…', $code = 'UTF-8'){
	if(F('getContent'.$arr['id'])){
		$str = F('getContent'.$arr['id']);
	}else{
		$arr = M('News') -> where(array('id' => $arr['id'])) ->Field('content') -> find();
		$str = $arr['content'];
		
		$str = cut_str(strip_tags($str), $sublen, $start = 0, $lastStr, $code = 'UTF-8');
		F('getContent'.$arr['id'], $str);
	}
    return $str;
}

/*
Utf-8、gb2312都支持的汉字截取函数 
cut_str(字符串, 截取长度, 开始长度, 编码); 
编码默认为 utf-8 
开始长度默认为 0 
*/
function cut_str($string, $sublen, $start = 0, $lastStr = '…', $code = 'UTF-8') {
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);
        if (count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)) . $lastStr;
        return join('', array_slice($t_string[0], $start, $sublen));
    } else {
        $start = $start * 2;
        $sublen = $sublen * 2;
        $strlen = strlen($string);
        $tmpstr = '';
        for ($i = 0; $i < $strlen; $i++) {
            if ($i >= $start && $i < ($start + $sublen)) {
                if (ord(substr($string, $i, 1)) > 129) {
                    $tmpstr.= substr($string, $i, 2);
                } else {
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if (ord(substr($string, $i, 1)) > 129) $i++;
        }
        if (strlen($tmpstr) < $strlen) $tmpstr.= $lastStr;
        return $tmpstr;
    }
}
/**
 * CURL发送请求
 *
 * @param string $url
 * @param mixed $data
 * @param string $method
 * @param string $cookieFile
 * @param array $headers
 * @param int $connectTimeout
 * @param int $readTimeout
 */
function curlRequest($url, $data = '', $method = 'POST', $cookieFile = '', $headers = '', $connectTimeout = 30, $readTimeout = 30) {
    $method = strtoupper($method);
    if (!function_exists('curl_init')) return socketRequest($url, $data, $method, $cookieFile, $connectTimeout);
    $option = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_CONNECTTIMEOUT => $connectTimeout,
        CURLOPT_TIMEOUT => $readTimeout
    );
    if ($headers) $option[CURLOPT_HTTPHEADER] = $headers;
    if ($cookieFile) {
        $option[CURLOPT_COOKIEJAR] = $cookieFile;
        $option[CURLOPT_COOKIEFILE] = $cookieFile;
    }
    if ($data && strtolower($method) == 'post') {
        $option[CURLOPT_POST] = 1;
        $option[CURLOPT_POSTFIELDS] = $data;
    }
    if (stripos($url, 'https://') !== false) {
        $option[CURLOPT_SSL_VERIFYPEER] = false;
        $option[CURLOPT_SSL_VERIFYHOST] = false;
    }
    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    //if (curl_errno($ch) > 0) throw_exception("CURL ERROR:$url " . curl_error($ch));
    curl_close($ch);
    return $response;
}
//生成返回华泰数据访问对象
function HtM($table) {
    M()->db(1, "sqlsrv://" . C('MS_DB_USER') . ":" . C('MS_DB_PWD') . "@" . C('MS_DB_HOST') . ":" . C('MS_DB_PORT') . "/" . C('MS_DB_NAME'));
    return M()->table($table);
}
// 循环创建目录
function mk_dir($dir, $mode = 0777) {
    if (is_dir($dir) || @mkdir($dir, $mode)) return true;
    if (!mk_dir(dirname($dir) , $mode)) return false;
    return @mkdir($dir, $mode);
}
/**************************************************************
 *
 *    使用特定function对数组中所有元素做处理
 *    @param  string  &$array     要处理的字符串
 *    @param  string  $function   要执行的函数
 *    @return boolean $apply_to_keys_also     是否也应用到key上
 *    @access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}
/**************************************************************
 *
 *    将数组转换为JSON字符串（兼容中文）
 *    @param  array   $array      要转换的数组
 *    @return string      转换得到的json字符串
 *    @access public
 *
 *************************************************************/
function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

function findNum($str=''){
        $str=trim($str);
        $str=str_replace('px','',$str);
        return $str*1;
    }

function getExtendsData($id, $type){
	if($type == 0){
		return getNewsExtends($id);
	}else{
		return getProductExtends($id);
	}
}
//news扩展获取一条记录
function getNewsExtends($news_id) {
    if (F('extends_news' . $news_id)) {
        return F('extends_news' . $news_id);
    } else {
        $data = array();
        $extend = M("News_extends")->where(array(
            'news_id' => $news_id
        ))->select();
        foreach ($extend as $k => $v) {
            $data[$v['name']] = $v['val'];
        }
        F('extends_news' . $news_id, $data);
        return $data;
    }
}
//product扩展获取一条记录
function getProductExtends($product_id){
	if (F('extends_product' . $product_id)) {
        return F('extends_product' . $product_id);
    } else {
        $data = array();
        $extend = M("Product_extends")->where(array(
            'product_id' => $product_id
        ))->select();
        foreach ($extend as $k => $v) {
            $data[$v['name']] = $v['val'];
        }
        F('extends_product' . $product_id, $data);
        return $data;
    }
}
//生成订单号
function build_order_no(){
	return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).__SITEID__;
}
//kindeditor上传集成
function alert($msg) {
	header('Content-type: text/html; charset=UTF-8');
	import('@.ORG.JSON');
	$json = new Services_JSON();
	echo $json->encode(array('error' => 1, 'message' => $msg));
	exit;
}
//根据用户ID返回回答数
function getAnswerNumByMid($id){
	return M('Info_ev')->where(array('member_id' => $id,'site_id' => __SITEID__))->count();
}
//
function getAnswerNumYesByMid($id){
	return M('Info_ev')->where(array('member_id' => $id,'yes'=>array('gt',0),'site_id' => __SITEID__))->count();
}
function getQuestionNum($id){
	return M('Info')->where(array('type'=>'question','site_id' => __SITEID__, 'member_id' => $id))->count();
}
//根据info_id返回回答数
function getAnswerNum($id){
	return M('Info_ev')->where(array('info_id' => $id,'site_id' => __SITEID__))->count();
}
//获取会员发布文章的数量
function getArtNum($id){
	return M('Info')->where(array('type'=>'art','site_id' => __SITEID__, 'member_id' => $id))->count();
}
//获取等级 
function getVip($socre){
	return intval(sqrt($socre));
	
}
/**
 * 
 * 根据php的$_SERVER['HTTP_USER_AGENT'] 中各种浏览器访问时所包含各个浏览器特定的字符串来判断是属于PC还是移动端
 * @author           discuz3x
 * @lastmodify    2014-04-09
 * @return  BOOL
 */
function checkmobile() {
 global $_G;
 $mobile = array();
//各个触控浏览器中$_SERVER['HTTP_USER_AGENT']所包含的字符串数组
 static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
    'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
    'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
    'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
    'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
    'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
    'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
//window手机浏览器数组【猜的】
 static $mobilebrowser_list =array('windows phone');
//wap浏览器中$_SERVER['HTTP_USER_AGENT']所包含的字符串数组
 static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
   'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
   'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
 $pad_list = array('pad', 'gt-p1000');
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
 if(dstrpos($useragent, $pad_list)) {
  return false;
 }
 if(($v = dstrpos($useragent, $mobilebrowser_list, true))){
  $_G['mobile'] = $v;
  return '1';
 }
 if(($v = dstrpos($useragent, $touchbrowser_list, true))){
  $_G['mobile'] = $v;
  return '2';
 }
 if(($v = dstrpos($useragent, $wmlbrowser_list))) {
  $_G['mobile'] = $v;
  return '3'; //wml版
 }
 $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
 if(dstrpos($useragent, $brower)) return false;
 $_G['mobile'] = 'unknown';
//对于未知类型的浏览器，通过$_GET['mobile']参数来决定是否是手机浏览器
 if(isset($_G['mobiletpl'][$_GET['mobile']])) {
  return true;
 } else {
  return false;
 }
}
/**
 * 判断$arr中元素字符串是否有出现在$string中
 * @param  $string     $_SERVER['HTTP_USER_AGENT'] 
 * @param  $arr          各中浏览器$_SERVER['HTTP_USER_AGENT']中必定会包含的字符串
 * @param  $returnvalue 返回浏览器名称还是返回布尔值，true为返回浏览器名称，false为返回布尔值【默认】
 * @author           discuz3x
 * @lastmodify    2014-04-09
 */
function dstrpos($string, $arr, $returnvalue = false) {
 if(empty($string)) return false;
 foreach((array)$arr as $v) {
  if(strpos($string, $v) !== false) {
   $return = $returnvalue ? $v : true;
   return $return;
  }
 }
 return false;
}

 //判断手机还是电脑访问网站方法一：
  function isMobile()
{ 
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    } 
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    { 
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    } 
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
            ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        } 
    } 
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    { 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        } 
    } 
    return false;
}

//生成文章页链接
function getArtLink($id, $type = 0){
	if($type == 0){
		$ret = M('News') ->alias('n') -> join("left join __CATEGORY__ AS c on c.id = n.category_id") -> where(array('n.id'=> $id)) -> Field("n.id,c.name,n.outlink") -> find();
		
		if($ret['outlink']){
			$returl = $ret['outlink'];
		}else{
			$returl = U('Home/'.$ret['name'].'/'.$ret['id'],array(), true, false, true, __SITEID__); 
		}
		if(!$ret){
			$returl = '';
		}
	}else{
		$pdb = M('Product');
		$ret = $pdb ->alias('n') -> join("left join __PRODUCT_CATEGORY__ AS c on c.id = n.category_id") -> where(array('n.id'=> $id)) -> Field("n.id,c.name,n.out_link") -> find();

		if($ret['out_link']){
			$returl = $ret['out_link'];
		}else{
			$returl = U('Home/'.$ret['name'].'/'.$ret['id']);
			if($ret['name'] == ''){
				$returl = U('Product/index', array('id' => $ret['id']));
			}
		}
		if(!$ret){
			$returl = '';
		}
	}
	
	return $returl;
}

//获取模块导航数据
function getNavData($modules_id){
	$db = D('Nav');
	return $db -> where(array('modules_id' => $modules_id, 'pid' => 0)) -> order('sort')-> select();
	
	
	if(F('NavData'.$modules_id)){
		return F('NavData'.$modules_id);
	}else{$db = D('Nav');
		$list = $db -> where(array('modules_id' => $modules_id, 'pid' => 0)) -> order('sort')-> select();
		F('NavData'.$modules_id, $list);
		return F('NavData'.$modules_id);
	}
}//获取模块导航数据(子级导航)
function getNavSubData($modules_id, $pid){
	$db = D('Nav');
	return $db -> where(array('modules_id' => $modules_id, 'pid' => $pid)) -> order('sort')-> select();
}
//根据列表数据名获取数据
function getModulesListData($name){
	switch($name){
		case 'list' : ''; break;
	}
}
//模块无限级导航
function getModulesMultiNavTree($pid,$class='') {
    $str = '';
    $cate = M('Nav');
    $re = $cate->where(array(
        'status' => 1,
        'pid' => $pid,
        'site_id' => __SITEID__
    ))->order('sort')->select();
    if (!is_array($re)) {
        return $re;
    } else {
        foreach ($re as $k => $v) {
			if($v['target'] == 0){
				$target = '';
			}else{
				$target = '_blank';
			}
			if($v['img_url'] == ''){
				$img = '';
			}else{
				$img = '';
			}
            $str.= '<li><a style="position:relative;" href="' . $v['link'] . '" target="'.$target.'" title="'.$v['title'].'">' . $v['title'] .$img. '</a>';
            $str.= getModulesMultiNavTree($v['id'], $class);
            $str.= '</li>';
        }
        return '<ul class="'.$class.'">' . $str . '</ul>';
    }
}

//获取客户端设备的类型 
function get_device_type(){
  $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  $type = 'other';
  if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
   $type = 'ios';
  }
  if(strpos($agent, 'android')){
   $type = 'android';
  }
  return $type;
 }


function parseTemplateData($dataname, $data){
	$arr = explode('.',$dataname);
    unset($arr[0]);
	foreach($arr as $v){
		$data = $data[$v]; 
	}
	return $data;
}





//刷新模块数据
function reloadModulesList($data, $siteid){
	$db = D('Modules');
	$newsdb = D('News');
	$catedb = D('Category');
	$pcatedb = D('Product_category');
	$pdb = D('Product');
	//$data = $db -> where(array('id' => $id)) -> find();
	if($data !== false){
		//文章表
		if($data['type'] == 1 || $data['type'] == 2 || $data['type'] == 10){
			$list = unserialize($data['content']);
			$ret = array();

			foreach($list as $v){
				if($v['module'] == 0){
				    $one = $newsdb->where(array('id' => $v['id'], 'site_id' => $siteid, 'status' => 1))-> Field(array_keys($v))->find();
				}else{
					$one = $pdb->where(array('id' => $v['id'], 'site_id' => $siteid, 'status' => 1))-> Field(array_keys($v))->find();
				}
				if($one){
					$ret[] = $one;
				}
			}
			$db -> where(array('id' => $data['id'])) -> data(array('content' => serialize($ret))) -> save();
		}
		
		//分类列表
		if($data['type'] == 12){
			$list = unserialize($data['content']);
			$ret = array();
			foreach($list as $v){
				if($v['module'] == 0){
				    $one = $catedb->where(array('id' => $v['id'], 'site_id' => $siteid, 'status' => 1)) -> Field(array_keys($v)) ->find();
				}else{
					$one = $pcatedb->where(array('id' => $v['id'], 'site_id' => $siteid, 'status' => 1)) -> Field(array_keys($v)) ->find();
				}
				if($one){
					$ret[] = $one;
				}
			}
			$db -> where(array('id' => $data['id'])) -> data(array('content' => serialize($ret))) -> save();
		}
	}
}


// 万能表单的内部标签处理
function fieldDispose($field){
		
		//单选按钮或者其他特殊按钮 就将值集合保存在此
		//$valueList = '';
		
		//表单id属性值数据
		$fid = $field['f_id'];
		
		//表单name属性值数据
		$fname = $field['f_name'];
		$name = $field['name'];
		//表单验证正则表达式数据
		$verify = $field['verify'];
		
		//表单验证信息数据
		$verifyHint = $field['verify_hint'];
		
		//表单type属性值数据
		$type = '';//默认为text
		if($field['f_type']==1){//文本框
			$type = 'text';
			$inputs = '<input style="width:100%;" class="decorate" placeholder="'.$name.'" id="'.$fid.'" name="'.$fname.'" type="'.$type.'" datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'" />';
		}else if($field['f_type']==2){//文件域
			$type ='file';
			$inputs = '<input enctype="multipart/form-data" id="'.$fid.'" name="'.$fname.'" type="'.$type.'" datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'" />';
		
		}else if($field['f_type']==3){//单选按钮
			$type ='radio';
			foreach(unserialize($field['valueList']) as $v){
				$inputs .= '<div style="display:inline-block; padding-bottom:5px;"><input id="'.$v['val'].'" value="'.$v['lebal'].'" name="'.$fid.'" type="'.$type.'" datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'" /><label style="margin-right:1em; margin-left:0.5em; margin-bottom:0;">'.$v['lebal'].'</label></div>';	
			}
				return $inputs;
			
		}else if($field['f_type']==4){//复选按钮
			$type ='checkbox';
			$i = 0;
			foreach(unserialize($field['valueList']) as $v){
				if($i == 0){
					$checked = 'checked="checked"';
				}
				$inputs .= '<input id="'.$v['val'].'" value="'.$v['lebal'].'" name="'.$fid.'[]" type="'.$type.'" nullmsg="'.$verifyHint.'" datatype="'.$verify.'" errormsg="'.$verifyHint.'" /><span>'.$v['lebal'].'</span>';
				$i ++ ;
			}
				return $inputs;
			}else if($field['f_type']==5){//文本域
				$inputs .= '<textarea id="'.$v['val'].'" value="'.$v['lebal'].'" name="'.$fid.'[]" type="'.$type.'" nullmsg="'.$verifyHint.'" datatype="'.$verify.'" errormsg="'.$verifyHint.'"></textarea>';
				return $inputs;
			}else if($field['f_type']==6){
				//验证码
				$inputs .= '<img id="verify_img" style="border:1px solid #ccc;" src="'.U('Admin/Public/verify').'" onclick="this.src=\''.U('Admin/Public/verify').'?\'+new Date().getTime()">';
		    }else if($field['f_type']==7){
				//验证码
				$inputs .= '<button type="submit">'.$name.'</button>';
		    }elseif($field['f_type']==8){
				$inputs = '<input style="width:100%;" class="decorate" placeholder="'.$name.'" id="'.$fid.'" name="'.$fname.'" type="'.$type.'" datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'" onclick="WdatePicker();" />';
			}
		
		return $inputs; 
	}

// 万能表单的内部标签处理
// $type 是否生成HTML，1生成HTML，0生成纯字符（用于结果查看和信息提示）
function fieldDisposebootstrap($field, $view = NULL, $data = NULL, $createselectlist = 1, $type = 1){
		//单选按钮或者其他特殊按钮 就将值集合保存在此
		if($type == 0){
			return $field['name']."：".$data."\n\r";
		}
		//表单id属性值数据
		$fid = $field['f_id'];
		//表单name属性值数据
		$fname = $field['f_name'];
		$name = $field['name'];
		//表单验证正则表达式数据
		$verify = $field['verify'];
		//表单验证信息数据
		$verifyHint = $field['verify_hint'];
		
		if($verify != ''){
			$verifystr = 'datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'"';
		}else{
			$verifystr = '';
		}
		//表单type属性值数据
		$type = '';//默认为text
		if($field['f_type']==1){//文本框
			$type = 'text';
			$inputs = '<input style="width:100%;" class="decorate form-control" value="'.$data.'" placeholder="'.$name.'" id="'.$fid.'" name="'.$fname.'" type="'.$type.'" '.$verifystr.' />';
		}else if($field['f_type']==2){//文件域
			$type ='file';
			$inputs = '<input enctype="multipart/form-data" id="'.$fid.'" name="'.$fname.'" type="'.$type.'" '.$verifystr.' />';
		
		}else if($field['f_type']==3){//单选按钮
			$type ='radio';
			foreach(unserialize($field['valueList']) as $v){
				//$inputs .= '<div style="display:inline-block; padding-bottom:5px;"><input id="'.$v['val'].'" value="'.$v['lebal'].'" name="'.$fid.'" type="'.$type.'" datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'" /><label style="margin-right:1em; margin-left:0.5em; margin-bottom:0;">'.$v['lebal'].'</label></div>';
				$checked = '';
				if($data == $v['val']){
					$checked = ' checked="checked"';
				}
				$inputs .= '<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="'.$v['val'].'" value="'.$v['val'].'" name="'.$fid.'"'.$checked.' type="'.$type.'" '.$verifystr.' /><span>'.$v['lebal'].'</span></label>';
			}
				return $inputs;
			
		}else if($field['f_type']==4){//复选按钮
			$type ='checkbox';
			$i = 0;
			foreach(unserialize($field['valueList']) as $v){
				$checked = '';
				if($data == $v['val']){
					$checked = ' checked="checked"';
				}
				/*if($i == 0){
					$checked = 'checked="checked"';
				}*/
				
				
				
				$inputs .= '<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="'.$v['val'].'" value="'.$v['val'].'" name="'.$fid.'[]"'.$checked.' type="'.$type.'" '.$verifystr.' /><span>'.$v['lebal'].'</span></label>';
				$i ++ ;
			}
				return $inputs;
			}else if($field['f_type']==5){//文本域
				$inputs .= '<textarea class="form-control" id="'.$v['val'].'" name="'.$fid.'" type="'.$type.'" '.$verifystr.' rows="5" >'.$data.'</textarea>';
				return $inputs;
			}else if($field['f_type']==6){
				//验证码
				$inputs .= '<img id="verify_img" style="border:1px solid #ccc;" src="'.U('Admin/Public/verify').'" onclick="this.src=\''.U('Admin/Public/verify').'?\'+new Date().getTime()">';
		    }else if($field['f_type']==7){
				//验证码
				$inputs .= '<button type="submit">'.$name.'</button>';
		    }elseif($field['f_type']==8){
				
				
				
				
				$inputs = '<input style="width:100%; cursor:pointer;" readonly value="'.($data == '' ? '' :date('Y-m-d H:i:s',$data)).'" class="scrollerinput decorate form-control datetimeinput" placeholder="'.$name.'" id="WdatePicker'.$field['id'].'" name="'.$fname.'" type="'.$type.'" '.$verifystr.' onclick="WdatePicker();" />';
				
				/*if(isMobile()){
					$inputs .= '<style>.dw{z-index:50000;}.dwo{z-index:50000;}</style><script>var curr = new Date().getFullYear();
            var opt = {

            }

            opt.date = {preset : \'date\'};
			opt.datetime = { preset : \'datetime\', minDate: new Date(1992,3,10,9,22), maxDate: new Date(2114,7,30,15,44), stepMinute: 5  };
			opt.time = {preset : \'time\'};
			opt.tree_list = {preset : \'list\', labels: [\'Region\', \'Country\', \'City\']};
			opt.image_text = {preset : \'list\', labels: [\'Cars\']};
			opt.select = {preset : \'select\'};
		$(\'#WdatePicker'.$field['id'].'\').scroller(\'destroy\').scroller($.extend(opt[\'datetime\'], { theme: \'android-ics light\', mode: \'scroller\', display: \'bottom\', lang: \'zh\' }));</script>';
		
				}*/
			}elseif($field['f_type']==10){
				$data = implode(',', $data);
				//if($data != ''){
					$fname = str_replace('_id', '', $fname);
				//}
				//$view->assign($fname, $data);
				
				$inputs = '<html:listselect class="btn btn-success btn-sm" name="'.$fname.'" multiple="1" url="'.U('Member/select').'" selected="'.$data.'" title="'.$name.'" id="'.$fname.'" />';
				if($createselectlist == 1){
					$inputs = $view -> fetch('',$inputs);
				}
				
				
			}elseif($field['f_type']==9){
				$data = implode(',', $data);
				//$view->assign($fname, $data);
				//if($data != ''){
					$fname = str_replace('_id', '', $fname);
				//}
				$inputs = '<html:listselect class="btn btn-success btn-sm" name="'.$fname.'" multiple="1" url="'.U('Customer/select').'" selected="'.$data.'" title="'.$name.'" id="'.$fname.'" />';
				if($createselectlist == 1){
					$inputs = $view -> fetch('',$inputs);
				}
				
			}elseif($field['f_type']==11){
				//if($data != ''){
					$fname = str_replace('_id', '', $fname);
				//}
				
				
				$inputs = '<html:listselect class="btn btn-success btn-sm" name="'.$fname.'" multiple="0" url="'.U('Member/select').'" selected="'.$data.'" title="'.$name.'(单选)" id="'.$fname.'" />';
				if($createselectlist == 1){
					$inputs = $view -> fetch('',$inputs);
				}
				
				
			}elseif($field['f_type']==12){
				//if($data != ''){
					$fname = str_replace('_id', '', $fname);
				//}
				$inputs = '<html:listselect class="btn btn-success btn-sm" name="'.$fname.'" multiple="0" url="'.U('Customer/select').'" selected="'.$data.'" title="'.$name.'(单选)" id="'.$fname.'" />';
				if($createselectlist == 1){
					$inputs = $view -> fetch('',$inputs);
				}
				
			}
		return $inputs; 
	}
/**发送微信信息方法
  * @openid 用户ID
  * @msg 信息内容
  */
function sendWXMsg($openid, $msg){
	Vendor('Weixin.Weixin');
	$d['token']=getSysVal('token');
	$d['appid']=getSysVal('appid');
	$d['appsecret']=getSysVal('appsecret');
	$weixin=new WeixinChat($d);
	$ret = $weixin -> sendCustomMessage($openid, $msg);
	if($ret){
		return true;
	}else{
		return false;
	}
}
//微信发送图片
function sendWXImg($openid, $msg){
	Vendor('Weixin.Weixin');
	$d['token']=getSysVal('token');
	$d['appid']=getSysVal('appid');
	$d['appsecret']=getSysVal('appsecret');
	$weixin=new WeixinChat($d);
	$ret = $weixin -> sendCustomMessage($openid, $msg, 'image');
	if($ret){
		return true;
	}else{
		return false;
	}
}

//微信发送图文
function sendWXNews($openid, $msg){
	Vendor('Weixin.Weixin');
	$d['token']=getSysVal('token');
	$d['appid']=getSysVal('appid');
	$d['appsecret']=getSysVal('appsecret');
	$weixin=new WeixinChat($d);
	$ret = $weixin -> sendCustomMessage($openid, $msg, 'news');
	if($ret){
		return true;
	}else{
		return false;
	}
}

/*  2017-5-23
*   因为以前发送短信模板的方法已经不能用了，改造了个新的LWNTempMsg
*	必须传id,id为模板消息的调用ID
*   $msg为array();
*	模板消息标题为first
*	模板消息的底部为remark
*	如果没有直接传array()，这个模板消息的要多少个字段就传多少，少了就会空
*/
function sendWXTempMsg($openid, $msg=array(),$id,$url=NULL){
	import("@.ORG.Sms.LWNTempMsg");
	$weixin=new LWNTempMsg($openid,$msg,$id,$url);
	$ret = $weixin -> sendMsg();

	if($ret){
		return true;
	}else{
		return false;

	}
}

//发送手机短信验证码
function sendSMSMsg($touser, $content){
	$Sms = C('SMSTYPE');
	import("@.ORG.Sms.".$Sms);
	$SObj = new $Sms();
	return $SObj -> templateSMS($touser, $content);
}


/**
 *创建场景二维码方法
 * @scene 场景标识号
 */
function createDimension($scene){
	Vendor('Weixin.Weixin');
	$d['token']=getSysVal('token');
	$d['appid']=getSysVal('appid');
	$d['appsecret']=getSysVal('appsecret');
	$weixin=new WeixinChat($d);
	$ticket = $weixin -> createQrcode($scene,1);
	return $weixin -> getQrcodeUrl($ticket['ticket']);//返回二维码的URL地址
}



//获取模块样式
function getModulesStyle($v){
	
	//宽度
	if(!empty($v['width'])){
		echo "width:".$v['width'].';';
	}
	//高度
	if(!empty($v['height'])){
		echo "height:".$v['height'].';';
	}
	//背景图
	if(!empty($v['backgroundimage'])){
		echo "background-image:url(".$v['backgroundimage'].');';
	}
	
	//背景图
	if(!empty($v['align']) && $v['align']!='margin:0 auto;'){
		echo "display:inline;";
		echo $v['align'];
	}
	//背景色
	if(!empty($v['backgroundcolor'])){
		echo "background-color:".$v['backgroundcolor'].';';
	}
	//背景位置
	if(!empty($v['backgroundPosition'])){
		echo "background-position:".$v['backgroundPosition'].';';
	}
	//背景重复
	if(!empty($v['backgroundrepeat'])){
		echo "background-repeat:".$v['backgroundrepeat'].';';
	}
	//边界
	if(!empty($v['margin'])){
		echo "margin:".$v['margin'].';';
	}
	
}
function getModulesTitleBorder($v){
	//边框
	if(!empty($v['titleBorderTop']) && $v['titleBorderTop'] != 'none'){
		echo $v['titleBorderTop'].';';
	}if(!empty($v['titleBorderRight']) && $v['titleBorderRight'] != 'none'){
		echo $v['titleBorderRight'].';';
	}if(!empty($v['titleBorderLeft']) && $v['titleBorderLeft'] != 'none'){
		echo $v['titleBorderLeft'].';';
	}if(!empty($v['titleBorderBottom']) && $v['titleBorderBottom'] != 'none'){
		echo $v['titleBorderBottom'].';';
	}
}
function getModulesListStyle($v){
	//字体大小
	if(!empty($v['listTitleFontSize'])){
		echo "font-size:".$v['listTitleFontSize'].';';
	}
	//字体颜色
	if(!empty($v['listTitleColor'])){
		echo "color:".$v['listTitleColor'].';';
	}
	
}
function getModulesBorder($v){
	//边框
	if(!empty($v['borderTop']) && $v['borderTop'] != 'none'){
		echo $v['borderTop'].';';
	}if(!empty($v['borderRight']) && $v['borderRight'] != 'none'){
		echo $v['borderRight'].';';
	}if(!empty($v['borderLeft']) && $v['borderLeft'] != 'none'){
		echo $v['borderLeft'].';';
	}if(!empty($v['borderBottom']) && $v['borderBottom'] != 'none'){
		echo $v['borderBottom'].';';
	}
}

//获取网站语言配置
function getLangConf($site_id){
	$ret = F('langConfig');
	if($ret){
		return $ret;
	}else{
		$db = M('Sitelang');
		$listRet = array();
		$list = $db -> where(array('site_id' => $site_id)) -> select();
		foreach($list as $v){
			$listRet[$v['key']] = $v['val'];
		}
		F('langConfig', $listRet);
		return $listRet;
	}
	
}
//获取后台用户信息
function getAdminName($id){
	$data = M('User') -> where(array('id' => $id)) -> find();
	return $data['nickname'];
}
//转换微信昵称中的特殊符号
function parseWeixinName($n){
	preg_match_all("/./u", $n, $arr);
	$nickname = '';
	Vendor('emoji.emoji');
	foreach($arr[0] as $v){
		$b = emoji_get_name($v);
		if($b == '?'){
			$nickname .= $v;
		}else{
			$nickname .= $b;
		}
	}
	return $nickname;
}

function inemoji($n){
	return base64_encode($n);
}

//还原特殊符号
function outemoji($n){
	return base64_decode($n);
}
//获取显示风格名称（后台）
function getTemplateName($id) {
	$pages = M('Pages') -> where(array('id' => $id)) -> find();
	if(empty($pages))return '无';
	return $pages['title'];
}

function curlDownload($remote,$local) {
	$cp = curl_init($remote);
	$file_content = curl_exec($cp);
	$fp = fopen($local,"w");
	curl_setopt($cp, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($cp, CURLOPT_FILE, $fp);
	curl_setopt($cp, CURLOPT_HEADER, 0);
	curl_exec($cp);
	curl_close($cp);
	@fclose($fp);
}

//生成二维码
function createaffqr($userInfo){
	$qrcodesetting = M('Site') -> where(array('id' => __SITEID__)) -> getField('qrcodesetting');
	
	$config = unserialize($qrcodesetting);
	if($userInfo['level'] == 0 && ($config['createQr']) == 0){
		sendWXMsg($userInfo['openid'], '请申请代理后方可生成我的二维码推广！');
		return false;
	}
	sendWXMsg($userInfo['openid'], '正在打造您的个人名片，请稍等……！');
	//import('ORG.Net.Http');
	//把二维码拉回到本地
	Vendor('Weixin.Weixin');
	$d['token'] = getSysVal('token');
	$d['appid'] = getSysVal('appid');
	$d['appsecret'] = getSysVal('appsecret');
	$weixin = new WeixinChat($d);
	//exit;
	$affid = 'aff_'.$userInfo['id'];
	
	//exit($affid);
	
	$tiket = $weixin->createQrcode($affid, 1);
	$qrocde =  'http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$tiket['ticket'];//exit($qrocde);
	$qrcodelocal = './Public/qrcode/'.$userInfo['id'].'/';
	//echo "<img src='".$qrocde."' />";
	if(!is_dir($qrcodelocal)){
		mkdir($qrcodelocal, 0777, true);
	}
	//拉取头像到本地
	import("ORG.Util.Image");
	//读取生成配置
	
	curlDownload($qrocde, $qrcodelocal.'qrcode.jpg');
	curlDownload($userInfo['img_url'], $qrcodelocal.'head.jpg');
	
	
	//$this->GrabImage($qrocde,$qrcodelocal.'qrcode.jpg');
	
	//二维码大小
	$qrsize = explode(',', $config['qrsize']);
	Image::thumb($qrcodelocal.'qrcode.jpg',$qrcodelocal.'qrcode.jpg','',$qrsize[0],$qrsize[1],true);
	//头像大小
	$headsize = explode(',', $config['headsize']);
	Image::thumb($qrcodelocal.'head.jpg',$qrcodelocal.'head.jpg','',$headsize[0],$headsize[1],true);
	
	//头像位置
	$headposition = explode(',', $config['headposition']);
	Image::water('./Public'.$config['qrbackground'], $qrcodelocal.'head.jpg', $qrcodelocal.'myqr.jpg', 100, $headposition[0], $headposition[1], false);
	
	
	//二维码位置
	$qrposition = explode(',', $config['qrposition']);
	Image::water($qrcodelocal.'myqr.jpg', $qrcodelocal.'qrcode.jpg', $qrcodelocal.'myqr.jpg', 100, $qrposition[0], $qrposition[1], false);
	
	//Image::buildString('吴俊源', array(0,0,0), $qrcodelocal.'nickname.png', 'png', 0, false);
	
	Vendor('water.water');
	$markimg = new water($qrcodelocal.'myqr.jpg');
	//生成姓名
	
	$markimg->color = $config['nicknamecolor']; 
	$markimg->fontSize = $config['nicknamesize']; 
	$markimg->fontFile='./Public/MSYHBD.TTC';
	$nicknameposition = explode(',', $config['nicknameposition']);
	$markimg->setMarkPos($nicknameposition[0],$nicknameposition[1]);
	$markimg->appendTextMark($userInfo['nickname']);
	$markimg->write($qrcodelocal.'myqr.jpg');
	$weixin -> sendCustomMessage($userInfo['openid'], $qrcodelocal.'myqr.jpg', 'image');
	//发送信息
	@sendWXMsg($userInfo['openid'], $config['sendMsg']); 
}

//发送红包


/*正确返回数据
object(SimpleXMLElement)#11 (10) {
  ["return_code"] => string(7) "SUCCESS"
  ["return_msg"] => string(12) "发放成功"
  ["result_code"] => string(7) "SUCCESS"
  ["mch_billno"] => string(28) "1242096102201603151624549409"
  ["mch_id"] => string(10) "1242096102"
  ["wxappid"] => string(18) "wx2df70496802ffa71"
  ["re_openid"] => string(28) "oSWvqs2GUw2E62q66ZMymYNHVrFo"
  ["total_amount"] => string(3) "100"
  ["send_listid"] => string(28) "0010214925201603150613364532"
  ["send_time"] => string(14) "20160315162511"
}
错误返回数据
object(SimpleXMLElement)#11 (10) {
  ["return_code"] => string(7) "SUCCESS"
  ["return_msg"] => string(54) "参数错误:只能发放1.00块到200块钱的红包."
  ["result_code"] => string(4) "FAIL"
  ["err_code"] => string(11) "MONEY_LIMIT"
  ["err_code_des"] => string(54) "参数错误:只能发放1.00块到200块钱的红包."
  ["mch_billno"] => string(28) "1242096102201603151627558058"
  ["mch_id"] => string(10) "1242096102"
  ["wxappid"] => string(18) "wx2df70496802ffa71"
  ["re_openid"] => string(28) "oSWvqs2GUw2E62q66ZMymYNHVrFo"
  ["total_amount"] => string(2) "10"
}
*/


function sendBonus($openid='', $money = 0, $site_id = 0){
	
	$bonusconfig = M('Site') -> where(array('id' => $site_id)) -> getField('bonusconfig');
	$bonusconfig = unserialize($bonusconfig);
	define('WX_APP_ID', $bonusconfig['appid']);
	define('WX_APP_SECRET', $bonusconfig['appsecret']);
	define('WX_APP_MCHID', $bonusconfig['mchid']);
	define('PARTNERKEY', $bonusconfig['PARTNERKEY']);
	define('HB_NICK_NAME', $bonusconfig['nick_name']);
	define('HB_SEND_NAME', $bonusconfig['send_name']);
	define('HB_WISHING', $bonusconfig['wishing']);
	
    define('APICLIENT_CERT', $bonusconfig['apiclient_cert']);
	define('APICLIENT_KEY', $bonusconfig['apiclient_key']);
	//dump($bonusconfig);
	Vendor('wxhb.oauth');
	$hb = new Wxapi();
	$ret = $hb -> pay($openid, $money);
	return $ret;
}
//检查URL正确性
function check_url($url){

    if(!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){

        return false;

    }

    return true;

}

//获地区名称
function getRegionById($id){
	if(!$id){return array(array('region_name' => ''));}
	return M('Region') -> where(array('region_id' => array('in', $id))) -> order('area_deep') -> select();
}

//在服务端换掉图片路径

function setDataOriginal($content){
	return preg_replace("/<!--[\w\W\r\n]*?-->/",'',$content);;
    return preg_replace('/(<img.+)src(=\"?.+)>/i',"\${1}data-original\${2}>",$content);
}


function replaceCss($style, $newstyle, $csspath = '', $media = ''){
	//处理不同分辨率下的CSS
	$mcr = array();
	$ocss = '';
	if($media != ''){
		$allstyle = $style;
		$style = getCssMediacss($style, $media);
		$mcr = getCssMediacssR($allstyle, $media);
		$ocss = replaceCssMedia($allstyle);
	}else{
		$allstyle = $style;
		$style = replaceCssMedia($style);
		$mcr = getCssMediacssR($allstyle, $media);
		//$style = replaceCssMedia($style);
	}
	//dump($mcr);exit;
	$pret = array();
	$ret = array();
	preg_match_all('/([a-zA-Z0-9:# \.,_-]|[(\{id\})]{4})+(?=\{)/', $style, $ret);
	
	
	$style = str_replace('{id}','',$style);
	$style = str_replace('("','(',$style);
	$style = str_replace('")',')',$style);
	preg_match_all('/\{[\s\.,\(\)a-zA-Z%:"\'#0-9;\/\-\!important]+\}/', $style, $pret);
	$css = '';
	$csspath = $csspath;
	$flag = true;
	foreach($ret[0] as $k => $v){
		//$v = trim($v, '{');
		if($v == $csspath){
			$css .= $csspath.'{'.$newstyle.'}';
			$flag = false;
		}else{
			$css .= $v.$pret[0][$k];
		}
		
	}
	if($flag){
		$css .= $csspath.'{'.$newstyle.'}';
	}
	if($media != ''){
		$css = $ocss.$media.'{'.$css.'}'.implode('',$mcr);
	}else{
		$css = $css.''.implode('',$mcr);
	}//dump($css);exit;
	
	//样式排序
	
	$style = sortCss($css);
	$style = str_replace('("','(',$style);
	$style = str_replace('")',')',$style);
	return $style;
}
function getCssMediacss($style, $media = ''){
	$tempcss = array();
	$mediare = str_replace('(','\(', $media);
	$mediare = str_replace(')', '\)', $mediare);
	preg_match_all('/'.$mediare.'[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/', $style, $tempcss);
	$style = str_replace($media,'',$tempcss[0][0]);
	$style = preg_replace('/(^[\s\{]+)|([\}][\s]{0,}$)/','',$style);
	return $style;
}
function getCssMediacssR($style, $media=''){
	if($media != ''){
		$mediare = str_replace('(','\(', $media);
		$mediare = str_replace(')', '\)', $mediare);
		$style = preg_replace('/'.$mediare.'[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/','',$style);
    }
	$tempcss = array();
	preg_match_all('/@media[a-z \(\)-:0-9]+[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/', $style, $tempcss);
	return $tempcss[0];
}


function sortCss($style){
	$tempcss = array();
	preg_match_all('/@media[a-z \(\)-:0-9]+[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/', $style, $tempcss);
	$css = preg_replace('/@media[a-z \(\)-:0-9]+[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/','',$style);
	$mcss = $tempcss[0];
	
	rsort($mcss);
	return $css.implode('',$mcss);
}

function getCssMedia($style){
	$ret = array();
	preg_match_all('/@media[a-z \(\)-:0-9]+/', $style, $ret);
	return $ret[0];
}
function replaceCssMedia($style){
	return preg_replace('/@media[a-z \(\)-:0-9]+[\s]{0,}\{[a-zA-Z -;,\.\{\}0-9\s]+\}[\s]{0,}\}/','',$style);
}
function getCss($style, $csspath = '', $media = ''){
	$mcr = array();
	$ocss = '';
	if($media != ''){
		$style = getCssMediacss($style, $media);
	}else{
		$style = replaceCssMedia($style);
	}
	$pret = $ret = array();
	$style = str_replace('("',"(",$style);
	$style = str_replace('")',')',$style);
	preg_match_all('/([a-zA-Z0-9:# \.,_-]|[(\{id\})]{4})+(?=\{)/', $style, $ret);
	preg_match_all('/\{[\s\.,\(\)a-zA-Z%:"\'\/#0-9;\-\!important]+\}/', str_replace('{id}','',$style), $pret);
	$css = '';
	foreach($ret[0] as $k => $v){
		//$v = trim($v, '{');
		if($v == $csspath){
			$css = $pret[0][$k];
		}
		
	}
	$css = str_replace('"',"'",$css);
	$css = str_replace('}', '', $css);
	$css = str_replace('{', '', $css);
	return $css;
}
function getCssPath($style, $media = ''){
	$mcr = array();
	$ocss = '';
	if($media != ''){
		$style = getCssMediacss($style, $media);
	}else{
		$style = replaceCssMedia($style);
	}
	$ret = array();
	preg_match_all('/([a-zA-Z0-9:# \.,_-]|[(\{id\})]{4})+(?=\{)/', $style, $ret);
	return $ret[0];
}

//快递名称 
function getShippingName($id){
	$title = M('Shipping') -> where(array('id' => $id)) -> getField('title');
	if($title){
		return $title;
	}
	return '无物流';
}

//计算订单剩余时间
function GetRTime($endtime){
 $nowtime = time();
 $endday = $endtime - $nowtime;
  if($endday < 0){
	 $endday = 0; 
  }else{
     $endday = round($endday/86400,0);
  }
 return  $endday;
 
}

function MyScandir($FilePath = './', $Order = 0) {
	$FilePath = opendir($FilePath);
	while (false !== ($filename = readdir($FilePath))) {
		$FileAndFolderAyy[] = $filename;
	}
	$Order == 0 ? sort($FileAndFolderAyy) : rsort($FileAndFolderAyy);
	return $FileAndFolderAyy;
}

//获取供货商名称
function getSupplier($id){
	$ret = M('Supplier') -> where(array('id' => $id)) -> getField('susername');
	$type=D('Supplier')->where(array('id'=>$id))->getField('type');
	switch ($type){
        case '1':$type='线上';break;
        case '2':$type='线下';break;
    }
	if($ret == ''){
		$ret = '无供货商';
	}
	return $ret.'('.$type.')';
}

//是否是蜘蛛访问
function is_spider(){
	
    $robots = array("baiduspider","googlebot","sosospider","360spider","slurp","yodaobot","sogou","msnbot","bingbot");
    $is_spider=false;
    $agent= strtolower($_SERVER["HTTP_USER_AGENT"]);
    foreach($robots as $user_agent){
        if(ereg($user_agent,$agent))
        {
            $is_spider=true;
        }
    }
    return $is_spider; 
}

/**
*微信分享记录
*
*@param int $site_id
*@param int $member_id
*@param int $aff_id 分享人ID
**/
function weixinshare_log($aff_id = 0){
    if(intval($aff_id) == 0) return false;
    $map['member_id'] = $data['member_id'] = $_SESSION['memberInfo']['id'];
    $map['site_id'] = $data['site_id'] = __SITEID__;
    $map['aff_id'] = $data['aff_id'] = $aff_id;
    $map['url'] = $data['url'] = U();
    $data['ctime'] = time();
    $Log = M("Weixinshare_log");
    $log = $Log->where($map)->find();

    if(empty($log) && $Log->create($data) && $data['aff_id'] != $data['member_id']){
		
        $Log->add();
        return true;
    }else{
        return false;
    }
}

function is_weixin()
{
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
		return true;
	}
	return false;
}


//获取分类列表
function getCategories($pid = 0){
	
	$db = M('Product_category');
	$list = $db -> where(array('site_id' => __SITEID__, 'pid' => $pid)) -> select();
	foreach($list as $k => $v){
		$list[$k]['sub'] = $db -> where(array('site_id' => __SITEID__, 'pid' => $v['id'])) -> select();
		//$list[$k]['brands'] = $db -> where("id in('".trim($v['brands'])."')") -> limit('8') -> select();
	}
	return $list;
	
}
function getCategoriesBrands($id = 0){
	$db = M('Product_category');
	$brands = $db -> where(array('site_id' => __SITEID__, 'id' => $id)) -> getField('brands');
	$ids = explode(',',$brands);
	foreach($ids as $k => $v){
		$ids[$k] = intval($v);
	}
	$ids[] = 0;
	$list = M('Brand') -> where("id in(".implode(',', $ids).")") -> select();
	return $list;
	
}


/**
 * 时间戳格式化
 *
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL, $format = 'Y-m-d H:i') {
    if (empty ( $time ))
        return '';
    $time = $time === NULL ? NOW_TIME : intval ( $time );
    return date ( $format, $time );
}
function day_format($time = NULL) {
    return time_format ( $time, 'Y-m-d' );
}
function hour_format($time = NULL) {
    return time_format ( $time, 'H:i' );
}


// 导出表格
function exportExcel($data, $title=array(), $filename='order'){
    header("Content-type:application/vnd.ms-excel"); 
    header("Content-Disposition:attachment;filename=".$filename.".xls"); 
    $header = '<html xmlns:o="urn:schemas-microsoft-com:office:office" 
 xmlns:x="urn:schemas-microsoft-com:office:excel" 
 xmlns="http://www.w3.org/TR/REC-html40"> 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html> 
     <head> 
        <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> 
         <style id="Classeur1_16681_Styles"></style> 
     </head> 
     <body> 
         <div id="Classeur1_16681" align=center x:publishsource="Excel"> ';
    echo $header;
    $table = '<table x:str border=0 cellpadding=0 cellspacing=0 width=100% style="border-collapse: collapse">';
    if (!empty($title)){
        $table .= '<tr>';
        foreach ($title as $k => $v) {
            $table .= '<td class=xl2216681 nowrap>';
            $table .= $v;
            $table .= '</td>';
        }
        $table .='</tr>';
    }
    if (!empty($data)){
        foreach($data as $key=>&$val){
            $table .= '<tr>';
            foreach ($val as $ck => &$cv) {
                $table .= '<td class=xl2216681 nowrap>';
                $table .= $cv;
                $table .= '</td>';
            }
            $table .='</tr>';
        }
    } 
    echo $table; 
    $footer = '</div> 
     </body> 
 </html> ';
    echo $footer;
}

//过滤script标签
function deleteScript($str){
	return preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str);
}

//获取评论时间
function getEvaluateTime($time){
	$ret = time() - $time;
	$d = floor($ret / 24 / 3600);
	$h = floor($ret / 3600);
	$i = floor($ret / 60);
	$s = $ret;
	if($s >= 0){
		$str = '刚刚';
	}
	if($i > 0){
		$str = $i.'分钟前';
	}
	if($h > 0){
		$str = $h.'小时前';
	}
	if($d > 0){
	    if($d == 1){
			$str = '昨天　'.date('H:i', $time);
		}
		if($d == 2){
			$str = '前天　'.date('H:i', $time);
		}
		if($d > 2){
			$str = date('Y年m月d日　H:i', $time);
		}
		
	}
	return $str;
}

//判断一个组用户组是否有权限开启菜单
function getAccessMenu($AccessList = '', $group = '', $modules = '', $action = ''){
	if(empty($AccessList)){
		return true;
	}
	$group == '' && $group = GROUP_NAME;
	$modules == '' && $modules = MODULE_NAME;
	$action == '' && $action = ACTION_NAME;
	$ACL = $AccessList;
	if(in_array(strtoupper($group), array_keys($ACL))){
		$ACL = $ACL[strtoupper($group)];
		if(in_array(strtoupper($modules), array_keys($ACL))){
			$ACL = $ACL[strtoupper($modules)];
			if(in_array(strtoupper($action), array_keys($ACL))){
				return true;
			}
		}
	}
	return false;
}

function getBrowserVer(){
    import("@.ORG.Browser");
	$browser = new Browser();
	return $browser->getVersion();
}
function getBrowser(){
    import("@.ORG.Browser");
	$browser = new Browser();
	return $browser->getBrowser(); 
}

function trimall($str){
    $search = array(" ","　","\n","\r","\t");
    $replace = array("","","","","");
    return str_replace($search, $replace, $str);
}

function replacebr($str, $restr = '<br>'){
	$order = array("\r\n", "\n", "\r");
	$replace = $restr; 
	return str_replace($order, $replace, $str);
}
function replacelink($link){
	if(!(substr($link,0,7) == 'http://' || substr($link,0,8) == 'https://' || substr($link,0,7) == 'mailto:' || substr($link,0,4) == 'tel:' || substr($link,0,6) == 'skype:')){
		$link = "__APP__".$link;
	}
	return $link;
}

//获取一个商品列表，根据分类ID
function getGoodsByCategory_name($name, $limit = 1){
	$cid = M('Product_category') -> where(array('name' => $name)) -> getField('id');
	return M('Product') -> where(array('category_id' => $cid)) -> order('sort') -> limit($limit) -> Field('id,title,module,img_url,create_time,price,salecount,table_name') -> select();
}

//返回一个字符，用于xml标签扩展的
function returnret($ret){
	return $ret;
}
function writelog1($txt){
	   $siteid = GROUP_NAME.'-'.__SITEID__.'-'.intval($_SESSION[C('USER_AUTH_KEY')]);
	   if(!is_dir($_SERVER['DOCUMENT_ROOT'].'/syslog1/'.$siteid.'/')){
		   mkdir($_SERVER['DOCUMENT_ROOT'].'/syslog1/'.$siteid.'/', 511, true);
	   }
       $fp =  fopen($_SERVER['DOCUMENT_ROOT'].'/syslog1/'.$siteid.'/'.date('Y-m-d').'.log','ab+');
       fwrite($fp,"\r\n-------".date('Y-m-d H:i:s')."-------\r\nCOOKIE:".print_r($_COOKIE, true)."\r\nAJAX:".IS_AJAX."\r\nPOST:".IS_POST."\r\nGET:".IS_GET."\r\nURL:".__SELF__."\r\nIP:".get_client_ip()."\r\n操作用户ID：".intval($_SESSION[C('USER_AUTH_KEY')])."\r\n");
       fwrite($fp,$txt);
       fwrite($fp,"\r\n\r\n\r\n");
       fclose($fp);
}
function writelog($txt){
	   $siteid = GROUP_NAME.'-'.__SITEID__.'-'.intval($_SESSION[C('USER_AUTH_KEY')]);
	   if(!is_dir($_SERVER['DOCUMENT_ROOT'].'/syslog/'.$siteid.'/')){
		   mkdir($_SERVER['DOCUMENT_ROOT'].'/syslog/'.$siteid.'/', 511, true);
	   }
       $fp =  fopen($_SERVER['DOCUMENT_ROOT'].'/syslog/'.$siteid.'/'.date('Y-m-d').'.log','ab+');
       fwrite($fp,"\r\n-------".date('Y-m-d H:i:s')."-------\r\nCOOKIE:".print_r($_COOKIE, true)."\r\nAJAX:".IS_AJAX."\r\nPOST:".IS_POST."\r\nGET:".IS_GET."\r\nURL:".__SELF__."\r\nIP:".get_client_ip()."\r\n操作用户ID：".intval($_SESSION[C('USER_AUTH_KEY')])."\r\n");
       fwrite($fp,$txt);
       fwrite($fp,"\r\n\r\n\r\n");
       fclose($fp);
}
function microtime_float(){
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}
//发送短信验证码
function SMSSend($touser, $content){
	$db = M('Smsconfig');
	//__RELATEID__使用这个ID共享短信接口
	$ret = $db -> where(array('site_id' => 143)) -> find();
	if($ret){
		import("@.ORG.Sms.".$ret['classname']);
		$class = $ret['classname'];
	    $SObj = new $class();
		$result = $SObj -> templateSMS($touser, $content);
		//dump($result);
	    return $result;
	}else{
		return false;
	}
	
}

function encode_geohash($latitude, $longitude, $deep)
{
	$BASE32	= '0123456789bcdefghjkmnpqrstuvwxyz';
	$bits = array(16,8,4,2,1);
	$lat = array(-90.0, 90.0);
	$lon = array(-180.0, 180.0);
	
	$bit = $ch = $i = 0;
	$is_even = 1;
	$i = 0;
	$mid;
	$geohash = '';
	while($i < $deep)
	{
		if ($is_even)
		{
			$mid = ($lon[0] + $lon[1]) / 2;
			if($longitude > $mid)
			{
				$ch |= $bits[$bit];
				$lon[0] = $mid;
			}else{
				$lon[1] = $mid;
			}
 		} else{
			$mid = ($lat[0] + $lat[1]) / 2;
			if($latitude > $mid)
			{
				$ch |= $bits[$bit];
				$lat[0] = $mid;
			}else{
				$lat[1] = $mid;
			}
		}
		
		$is_even = !$is_even;
		if ($bit < 4)
			$bit++;
		else {
			$i++;
			$geohash .= $BASE32[$ch];
			$bit = 0;
			$ch = 0;
		}
	}
	return $geohash;
}

function decode_geohash($geohash)
{
	$geohash = strtolower($geohash);
	$BASE32	= '0123456789bcdefghjkmnpqrstuvwxyz';
	$bits = array(16,8,4,2,1);
	$lat = array(-90.0, 90.0);
	$lon = array(-180.0, 180.0);
	$hashlen = strlen($geohash);
	$is_even = 1;
	
	for($i = 0; $i < $hashlen; $i++ )
	{
		$of = strpos($BASE32,$geohash[$i]);
		for ($j=0; $j<5; $j++) {
			$mask = $bits[$j];
			if ($is_even) {
				$lon[!($of&$mask)] = ($lon[0] + $lon[1])/2;
			} else {
				$lat[!($of&$mask)] = ($lat[0] + $lat[1])/2;
			}
			$is_even = !$is_even;
		}
	}
	$point = array( 0 => ($lat[0] + $lat[1]) / 2, 1 => ($lon[0] + $lon[1]) / 2);
	return $point;
}

//自定义的mysql数据库缓存方法，全局通用，不分站点，于是name不能重复，主要用于微信扫码认证
function MCS($name, $value = NULL){
	if($value === NULL){
		return M('Cache') -> where(array('name' => $name)) -> getField('value');
	}else{
		return M('Cache') -> add(array('name' => $name, 'value' => $value));
	}
}

function getManagerList(){
	$ndb = M('Node');
	$gid = $ndb -> where(array('name' => 'Intesys', 'level' => 1)) -> getField('id');
	$mid = $ndb -> where(array('name' => 'IntesysManager', 'level' => 2)) -> getField('id');
	$aid = $ndb -> where(array('name' => 'IntesysManagerindex', 'level' => 3)) -> getField('id');
	$macdb = M(C('RBAC_ACCESS_TABLE'));
	$rsql = $macdb -> where("node_id = '".$gid."' or node_id = '".$mid."' or node_id = '".$aid."'") -> group('role_id') -> having('count(role_id) >= 3') -> Field('role_id') -> buildSql();
	//echo $macdb -> getLastSql();
	//dump($rsql);exit;
	$utdb = M(C('RBAC_USER_TABLE'));
	$list = $utdb -> where("site_id = ".__SITEID__." and role_id in(".$rsql.")") -> select();
	$ret = array();
	foreach($list as $k => $v){
		$ret[] = $v['user_id'];
	}
	return $ret;
}

//转换字符不与input 中的引号冲突
//$c要替换的字符
function htmlconvert($str){ 
	$str = str_replace('"', '&#34;', $str);
	$str = str_replace("'", '&#39;', $str);
	return $str;
}


function TMPLSTRIPSPACE($html){
	$html = preg_replace("/<!--[\w\W\r\n]*?-->/",'',$html);
	$find     = array("~>\s+<~","~>(\s+\n|\r)~");
	$replace  = array("><",">");
	$html = preg_replace($find, $replace, $html);
	return $html;
}

function addDetection($ActionName)
{
    $Detection = M("Detection");
    $str="http://weixin.xb363.com";
    $data['site_id'] = __SITEID__;
    $data['ActionName'] = $ActionName;
    $data['ActionTime'] = time();
    $data['url'] = $url = get_url($str, $rep);
    $data['member_id'] = $_SESSION[memberInfo][id];
    $Detection->add($data);
}

function get_url($str, $rep)
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return str_replace($str, $rep, $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url);
}

//返回一个员工的所有管理部门有返回数组，没有返回FALSE
function getposManagerList($member_id){
	$db = M('Member_position');
	$ret = $db -> where(array('member_id' => $member_id, 'site_id' => __SITEID__)) -> getField('id', true);
	if($ret){
		return $ret;
	}else{
		return false;
	}
}

function getmemberidbysupplier_id($supplierid){
	return M('Supplier') -> where(array('id' => $supplierid)) -> getField('member_id');
}


function hidtel($phone){
    $IsWhat = preg_match('/(0[0-9]{2,3}[-]?[2-9][0-9]{6,7}[-]?[0-9]?)/i',$phone); //固定电话
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[-]?[2-9])[0-9]{3,4}([0-9]{3}[-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}
function hideName($str){
    $length=mb_strlen($str,'utf8');
    if($length<=1){
        return $str;
    }

    if($length%2){
        $getlength=($length-1)/2;
        $restlength=$length-$getlength;
    }else{
        $getlength=$length/2;
        $restlength=$length-$getlength;
    }
    $str=mb_substr( $str, 0, $getlength, 'utf-8');

    $empty='*';
    $foot=str_pad($empty,$restlength,'*',STR_PAD_BOTH);
    return $str.$foot;
}